<template>
  <div class="app-container">
    <person-tool :selected.sync="selected" @new="handleNew" />
    <person-display :list="list" :selected="selected" @edit="handleEdit" @toggle="handleToggle" />
    <page :current.sync="current" :size="size" :total="total" />
    <course-detail :visible="visible" :data="form" @cancel="handleCancel" @confirm="handleConfirm" />
  </div>
</template>

<script>
import PersonTool from '@/views/components/PersonTool'
import PersonDisplay from '@/views/components/PersonDisplay'
import Page from '@/views/components/Page'
import CourseDetail from '@/views/components/CourseDetail'
import { page_person, query, save_update, toggle } from '@/api/course'

export default {
  name: 'Person',
  components: { PersonTool, PersonDisplay, Page, CourseDetail },
  data() {
    return {
      current: 1,
      size: 10,
      total: 0,
      list: [],
      selected: true,
      visible: false,
      form: {}
    }
  },
  watch: {
    current: {
      immediate: true,
      handler(newVal) {
        this.current = newVal
        this.handleCommon()
      }
    },
    is_selected: {
      immediate: true,
      handler(newVal) {
        this.handleCommon({ is_selected: newVal })
      }
    }
  },
  methods: {
    handleCommon(params) {
      page_person({ current: this.current, size: this.size, params }).then(res => {
        const { code, data } = res
        if (code === 20000) {
          this.total = data.total
          this.list = data.records
        }
      }).catch(err => this.$message.error(err))
    },
    handleNew() {
      this.visible = true
    },
    handleEdit(uid) {
      this.visible = true
      query(uid).then(res => {
        const { code, data } = res
        if (code === 20000) {
          this.form = data
        }
      }).catch(err => this.$message.error(err))
    },
    handleToggle(uid) {
      toggle(uid).then(res => {
        const { code, msg } = res
        if (code === 20000) {
          this.$message.success(msg)
          this.handleCommon()
        } else {
          this.$message.error(msg)
        }
      }).catch(err => this.$message.error(err))
    },
    handleCancel() {
      this.visible = false
    },
    handleConfirm(form) {
      save_update(form).then(response => {
        const { code, msg } = response
        if (code === 20000) {
          this.$message.success(msg)
          this.visible = false
          this.handleCommon()
        } else {
          this.$message.error(msg)
        }
      }).catch(err => this.$message.error(err))
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }

  .permission-tree {
    margin-bottom: 30px;
  }
}
</style>
